package com.cxf.lock;

import lombok.extern.log4j.Log4j;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 此版本是一个ZK分布式锁大概原理，解决V1版本的两个问题。细节之处根据业务修改。原题流程图查看该目录下的principle.jpg文件
 * 原理是不建立持久性节点，建立临时的顺序节点，这样客户端挂掉，节点自动销毁并释放锁，解决死锁问题
 * 后一个节点只监听前面一个节点。前面完成节点销毁，通知后面一个节点创建节点获取锁。解决惊群问题
 * @author xuanfei_Chen
 * @date 2020/4/5 5:33 下午
 */
@Log4j
public class ZookeeperLockV2 implements Lock {

    private static final String ZK_IP_PORT = "127.0.0.1:2181";
    private static final String LOCK_NODE = "/LOCK";

    private ZkClient client = new ZkClient(ZK_IP_PORT, 1000, 1000);
    private CountDownLatch cdl = null;

    private String beforePath; //当前请求的节点
    private String currentPath; //当前请求的节点前一个节点

    public ZookeeperLockV2(){
        if(!this.client.exists(LOCK_NODE)){
            this.client.createPersistent(LOCK_NODE);
        }
    }
    /**
     * 非阻塞性加锁
     * @Author:xuanfei_Chen
     * @Date:5:43 下午 2020/4/5
     */
    @Override
    public boolean tryLock() {
        // 如果currentPath为空则为第一次尝试加锁，第一次加锁赋值currentPath
        if(currentPath == null || currentPath.length() <= 0){
            // 创建一个临时顺序节点
            currentPath = this.client.createEphemeralSequential(LOCK_NODE + '/', "lock");
            log.warn("------------" + currentPath);
        }
        //获取所有临时节点并排序，临时节点名称为自增长的字符串。如：0000000400
        List<String> children = this.client.getChildren(LOCK_NODE);
        Collections.sort(children);

        // 如果当前节点在所有节点中，排名第一，则获取锁成功
        if(currentPath.equals(LOCK_NODE + '/' + children.get(0))){
            return true;
        //如果当前节点在所有节点中排名不是第一，则获取前面的节点名称，并赋值给beforePath
        } else {
            int wz = Collections.binarySearch(children, currentPath.substring(6));
            beforePath = LOCK_NODE + '/' +children.get(wz-1);
        }
        return false;
    }

    /**
     * 阻塞性加锁
     * @Author:xuanfei_Chen
     * @Date:5:43 下午 2020/4/5
     */
    @Override
    public void lock() {
        if(!tryLock()){
            waitForLock();
            lock();
        } else {
          log.warn(Thread.currentThread().getName() + "  获得分布式锁！");
        }

    }

    private void waitForLock() {
        IZkDataListener zkDataListener = new IZkDataListener() {

            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                log.warn(Thread.currentThread().getName() + ": 捕获到DataDelete事件！------");
                if(cdl != null){
                    cdl.countDown();
                }
            }
        };
        //给节点加监听
        client.subscribeDataChanges(beforePath, zkDataListener);
        if(client.exists(beforePath)){
            cdl = new CountDownLatch(1);
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        client.unsubscribeDataChanges(beforePath, zkDataListener);
    }

    /**
     * 解锁
     * @Author:xuanfei_Chen
     * @Date:5:43 下午 2020/4/5
     */
    @Override
    public void unlock() {
        client.delete(currentPath);
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }
}
